import { CacheService } from '@app/cache';
import { ConfigureService } from '@app/configure';
import { DictionaryCategory } from '@app/db/common/entities/DictionaryCategory';
import { DictionaryItem } from '@app/db/common/entities/DictionaryItem';
import { PlatformData } from '@app/db/common/entities/PlatformData';
import { Injectable } from '@nestjs/common';
import { Cron, Timeout } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { MoreThan, Repository } from 'typeorm';

@Injectable()
export class CommonService {
    public wxAccessTokenKey:string

    public wechatConf:{[key:string] : any};
    public alipayConf:{[key:string] : any};
    public wxAccessToken:string;

    private prvQueryTime = 0

    constructor(
        @InjectRepository(PlatformData, 'common') protected repository1:Repository<PlatformData>,
        @InjectRepository(DictionaryCategory, 'common') protected repository2:Repository<DictionaryCategory>,
        @InjectRepository(DictionaryItem, 'common') protected repository3:Repository<DictionaryItem>,
        private config:ConfigureService,
        private cache:CacheService
    ){
        this.wxAccessTokenKey = this.config.get('wxAccessTokenKey')
    }

    @Timeout(0)
    initConf(){
        this.conf()
    }

    @Cron('*/5 * * * *')
    async conf() {
        const time = Date.now()
        if((time - this.prvQueryTime) < 60000) return
        this.prvQueryTime = time
        const data = await this.repository1.find({
            select : ['wechat', 'alipay']
        })

        if(data.length > 0) {
            this.wechatConf = data[0].wechat
            this.alipayConf = data[0].alipay
        }

        const wxAccessToken = await this.cache.get(this.wxAccessTokenKey)
        if(wxAccessToken) {
            this.wxAccessToken = wxAccessToken
        }

    }

    async queryChargingStationLabels() {
        const category = await this.repository2.findOne({
            where : {code : 'CHARGE_STATION_LABEL'},
            select : ['id']
        })

        if(!category) return ''
        const items = await this.repository3.find({
            where : {categoryId : category.id},
            select : ['name', 'code']
        })

        const maps:{[key:string]:string} = {}
        items.forEach(item => {
            maps[item.code] = item.name
        })
        return maps
    }


    async queryChargeStopReason(reason:number) {
        const category = await this.repository2.findOne({
            where : {code : 'CHARGE_STOP_REASON'},
            select : ['id']
        })

        if(!category) return ''
        const item = await this.repository3.findOne({
            where : {code : String(reason), categoryId : category.id},
            select : ['name']
        })

        if(!item) return ''
        
        return item.name
    }

    async queryChargeFailReason(code:number) {
        const category = await this.repository2.findOne({
            where : {code : 'CHARGE_FAIL_REASON'},
            select : ['id']
        })

        if(!category) return ''
        const item = await this.repository3.findOne({
            where : {code : String(code), categoryId : category.id},
            select : ['name']
        })

        if(!item) return ''
        
        return item.name
    }

    async queryChargeFailReasons() :Promise<{[key:string]:string}>{
        const category = await this.repository2.findOne({
            where : {code : 'CHARGE_FAIL_REASON'},
            select : ['id']
        })

        if(!category) return {}
        const items = await this.repository3.find({
            where : {categoryId : category.id},
            select : ['name', 'code']
        })

        const res:{[key:string]:string} = {}

        items.forEach(item => {
            res[item.code] = item.name
        })

        return res
    }

    async queryChargeTemplate() {
        const res = await this.repository1.query("select wechat->>'chargeFinishMsgTemplate' AS t from platform_data limit 1")
        let t = ''
        if(res != null && res.length > 0) {
            t = res[0].t
        }

        return t
    }
}
